﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;


using Entity;

namespace SalesVMT
{
    public partial class frmSpend : Form
    {
        DialogResult dlgResult;
        SpendInfo Spendinf;
        public frmSpend(int _Spend_ID)
        {
            InitializeComponent();
            Spendinf = new SpendInfo();
            lblNo.Text = UISetting.AutoFillSpendCode();
            mtxSpendDate.Text = DateTime.Today.ToString("dd/MM/yyyy");
            
            DisplayFrame();
            UISetting.LoadProviderFromReceipt(ref cboProvider);
            Spendinf.Spend_ID = _Spend_ID;
            if (_Spend_ID > 0)
            {
                Spendinf = SpendDB.GetInfo(_Spend_ID);
                InfoToForm();
                LoadListBySpend();
                LockForm(false);
            }
            this.KeyPreview = true;
            dlgResult = DialogResult.Cancel;
            
        }
        private void DisplayFrame()
        {
            UISetting.AddColumn(ref dgvList1, "Receipt_ID", "Khóa", "", 1, false, true);
            UISetting.AddColumn(ref dgvList1, "RowNumber", "STT", "C", 35, true, true);
            UISetting.AddColumn(ref dgvList1, "Receipt_Code", "Phiếu NK", "", 90, true, true);
            UISetting.AddColumn(ref dgvList1, "Receipt_Date", "Ngày nhập", "C", 90, true, true);
            UISetting.AddColumn(ref dgvList1, "Receipt_DebitDays", "Số ngày nợ", "R", 90, true, true);
            UISetting.AddColumn(ref dgvList1, "Receipt_Total", "Tổng cộng", "R", 95, true, true);
            UISetting.AddColumn(ref dgvList1, "Receipt_Pay", "Đã trả", "R", 90, true, true);
            UISetting.AddColumn(ref dgvList1, "Remainder", "Còn nợ", "R", 90, true, true);
            UISetting.AddColumn(ref dgvList1, "Instalment", "Trả kỳ này", "R", 100, true, false);
        }
        private void FormToInfo()
        {
            Spendinf.Spend_Code = lblNo.Text;
            Spendinf.Spend_Date = DateTime.ParseExact(mtxSpendDate.Text, "dd/MM/yyyy", null);
            Spendinf.Spend_ProviderID = Convert.ToInt32(cboProvider.SelectedValue);
            Spendinf.Spend_Receive = txtReceive.Text;
            Spendinf.Spend_Reason = txtReason.Text;
            Spendinf.Spend_Total = Convert.ToDecimal(txtTotal.Text);
            Spendinf.Spend_UsersID = UsersDB.GetInfoByUsersName(Program.strUserName).Users_ID;
        }
        private void InfoToForm()
        {
            lblNo.Text = Spendinf.Spend_Code;
            mtxSpendDate.Text = Convert.ToDateTime(Spendinf.Spend_Date).ToString("dd/MM/yyyy");
            cboProvider.SelectedValue = Spendinf.Spend_ProviderID;
            txtReceive.Text = Spendinf.Spend_Receive;
            txtReason.Text = Spendinf.Spend_Reason;
            txtTotal.Text = Convert.ToDecimal(Spendinf.Spend_Total).ToString("N1");
        }

        private void LoadListByProvider()
        {
            
            dgvList1.Rows.Clear();
            DataTable _dt = new DataTable();
            _dt = ReceiptDB.GetAllByProviderForSpend(Convert.ToInt32(cboProvider.SelectedValue)).Tables[0];
            int n = _dt.Rows.Count;
            for (int i = 0; i < n; i++)
            {
                dgvList1.Rows.Insert(i, 1);
                dgvList1.Rows[i].Cells["RowNumber"].Value = i + 1;
                dgvList1.Rows[i].Cells["Receipt_ID"].Value = _dt.Rows[i]["Receipt_ID"].ToString();
                dgvList1.Rows[i].Cells["Receipt_Code"].Value = _dt.Rows[i]["Receipt_Code"].ToString();
                dgvList1.Rows[i].Cells["Receipt_Date"].Value = Convert.ToDateTime(_dt.Rows[i]["Receipt_Date"]).ToString("dd/MM/yyyy");
                dgvList1.Rows[i].Cells["Receipt_DebitDays"].Value = _dt.Rows[i]["Receipt_DebitDays"].ToString();
                dgvList1.Rows[i].Cells["Receipt_Total"].Value = Convert.ToDecimal(_dt.Rows[i]["Receipt_Total"]).ToString("N1");
                dgvList1.Rows[i].Cells["Receipt_Pay"].Value = Convert.ToDecimal(_dt.Rows[i]["Receipt_Pay"]).ToString("N1");
                dgvList1.Rows[i].Cells["Remainder"].Value = Convert.ToDecimal(Convert.ToDecimal(_dt.Rows[i]["Receipt_Total"]) - Convert.ToDecimal(_dt.Rows[i]["Receipt_Pay"])).ToString("N1");
                dgvList1.Rows[i].Cells["Instalment"].Value = 0;

            }
            
        }
        private void LoadListBySpend()
        {
            dgvList1.Rows.Clear();
            DataTable _dt = new DataTable();
            _dt = SpendDetailsDB.GetAllBySpend(Spendinf.Spend_ID).Tables[0];
            int n = _dt.Rows.Count;
            for (int i = 0; i < n; i++)
            {
                dgvList1.Rows.Insert(i, 1);
                dgvList1.Rows[i].Cells["RowNumber"].Value = i + 1;
                dgvList1.Rows[i].Cells["Receipt_ID"].Value = _dt.Rows[i]["Receipt_ID"].ToString();
                dgvList1.Rows[i].Cells["Receipt_Code"].Value = _dt.Rows[i]["Receipt_Code"].ToString();
                dgvList1.Rows[i].Cells["Receipt_Date"].Value = Convert.ToDateTime(_dt.Rows[i]["Receipt_Date"]).ToString("dd/MM/yyyy");
                dgvList1.Rows[i].Cells["Receipt_DebitDays"].Value = _dt.Rows[i]["SpendDetails_DebitDays"].ToString();
                dgvList1.Rows[i].Cells["Receipt_Total"].Value = Convert.ToDecimal(_dt.Rows[i]["Receipt_Total"]).ToString("N1");
                dgvList1.Rows[i].Cells["Receipt_Pay"].Value = Convert.ToDecimal(_dt.Rows[i]["SpendDetails_Pay"]).ToString("N1");
                dgvList1.Rows[i].Cells["Remainder"].Value = Convert.ToDecimal(Convert.ToDecimal(_dt.Rows[i]["Receipt_Total"]) - Convert.ToDecimal(_dt.Rows[i]["SpendDetails_Pay"])).ToString("N1");
                dgvList1.Rows[i].Cells["Instalment"].Value = Convert.ToDecimal(_dt.Rows[i]["SpendDetails_Instalment"]).ToString("N1");
            }

        }

        private SpendDetailsInfo[] ReadSpendDetails()
        {
            int n = dgvList1.Rows.Count;
            if (n > 0)
            {
                SpendDetailsInfo[] tracks = new SpendDetailsInfo[n];
                for (int i = 0; i < n; i++)
                {
                    tracks[i] = new SpendDetailsInfo();
                    tracks[i].SpendDetails_ReceiptID = Convert.ToInt32(dgvList1.Rows[i].Cells["Receipt_ID"].Value);
                    tracks[i].SpendDetails_DebitDays = Convert.ToInt32(dgvList1.Rows[i].Cells["Receipt_DebitDays"].Value);
                    tracks[i].SpendDetails_Pay = Convert.ToDecimal(dgvList1.Rows[i].Cells["Receipt_Pay"].Value);
                    tracks[i].SpendDetails_Instalment = Convert.ToDecimal(dgvList1.Rows[i].Cells["Instalment"].Value);
                }
                return tracks;
            }
            else
            {
                return null;
            }
        }
        private bool CheckValid()
        {
            decimal dec;
            if (!Decimal.TryParse(txtTotal.Text, out dec)||dec == 0)
            {
                Program.taskbarNotifier.Show(Message.Info, "Chưa có mặt hàng nào được trả kỳ này! Hãy nhập lại.", UIParamater.TimeToShow, UIParamater.TimeToStay, UIParamater.TimeToHide);
                return false;
            }

            return true;
        }
        private void LockForm(bool Lock)
        {
            cboProvider.Visible = Lock;
            lblProvider.Visible = !Lock;
            dgvList1.Columns["Instalment"].ReadOnly = !Lock;
        }

        private void TotalRowsPrice()
        {
            decimal Total = 0;
            for (int i = 0; i < dgvList1.Rows.Count; i++)
            {
                Total += Convert.ToDecimal(dgvList1.Rows[i].Cells["Instalment"].Value);
            }
            txtTotal.Text = Total.ToString("N1");
        }

        private void dgvList1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            decimal newDecimal;
            decimal Receipt_Total = Convert.ToDecimal(dgvList1.Rows[e.RowIndex].Cells["Receipt_Total"].Value);
            decimal Receipt_Pay = Convert.ToDecimal(dgvList1.Rows[e.RowIndex].Cells["Receipt_Pay"].Value);

            if (e.ColumnIndex == dgvList1.Columns["Instalment"].Index)
            {

                if (!decimal.TryParse(e.FormattedValue.ToString(), out newDecimal) || newDecimal < 0)
                {
                    e.Cancel = true;
                    Program.taskbarNotifier.Show(Message.Info, "Đơn giá phải là số dương", UIParamater.TimeToShow, UIParamater.TimeToStay, UIParamater.TimeToHide);
                }
                else if (newDecimal > Receipt_Total - Receipt_Pay)
                {
                    e.Cancel = true;
                    Program.taskbarNotifier.Show(Message.Info, "Số lượng không được vượt giá trị ''Còn lại''", UIParamater.TimeToShow, UIParamater.TimeToStay, UIParamater.TimeToHide);
                }
            }
          
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (!CheckValid())
                return;
            FormToInfo();
            SpendDetailsInfo[] tracks = ReadSpendDetails();
            if (tracks == null)
            {
                Program.taskbarNotifier.Show(Message.Info, "Chưa có mặt hàng nào được nhập! Hãy nhập lại.", UIParamater.TimeToShow, UIParamater.TimeToStay, UIParamater.TimeToHide);
                return;
            }
            if (Spendinf.Spend_ID > 0)
            {
                if (SpendDB.Update(Spendinf))
                {
                    Program.taskbarNotifier.Show(Message.Info, Message.Update_Complete, UIParamater.TimeToShow, UIParamater.TimeToStay, UIParamater.TimeToHide);
                    dlgResult = DialogResult.OK;
                }
                else
                    MessageBox.Show(Message.Update_Error, Message.Info, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                Spendinf.Spend_ID = SpendDB.Insert(Spendinf);
                if (Spendinf.Spend_ID > 0)
                {
                    LockForm(false);
                    for (int i = 0; i < tracks.Length; i++)
                    {
                        tracks[i].SpendDetails_SpendID = Spendinf.Spend_ID;
                        if (SpendDetailsDB.Insert(tracks[i]) > 0)
                        {
                            Program.taskbarNotifier.Show(Message.Info, Message.Create_Complete, UIParamater.TimeToShow, UIParamater.TimeToStay, UIParamater.TimeToHide);
                            dlgResult = DialogResult.OK;
                        }
                        else
                            MessageBox.Show(Message.Create_Error, Message.Info, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                else
                    MessageBox.Show(Message.Create_Error, Message.Info, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            if (Spendinf.Spend_ID == 0)
            {
                Program.taskbarNotifier.Show(Message.Info, "Cần phải lưu dữ liệu trước khi in!", UIParamater.TimeToShow, UIParamater.TimeToStay, UIParamater.TimeToHide);
                return;
            }
                frmReport f = new frmReport("PHIEU CHI", new string[] { Spendinf.Spend_ID.ToString(), "Phiếu chi"});
                f.Show();
        }
        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Dispose();
            this.Close();
        }

        private void frmSpend_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.DialogResult = dlgResult;
        }

        private void btnNew_Click(object sender, EventArgs e)
        {
            Spendinf.Spend_ID = 0;
            lblNo.Text = UISetting.AutoFillSpendCode();
            mtxSpendDate.Text = DateTime.Today.ToString("dd/MM/yyyy");
            txtReceive.Text = "";
            if(cboProvider.Text != "")
                cboProvider.SelectedIndex = 0;
            LoadListByProvider();
            txtTotal.Text = "0.0";
            LockForm(true);
        }

        private void frmSpend_KeyUp(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.Enter:
                    if (!e.Alt && !e.Control && !dgvList1.Focused)
                    {
                        this.ProcessTabKey(!e.Shift);
                        e.Handled = true;
                    }
                    break;
                case Keys.F2:
                    btnNew_Click(null, null);
                    break;
                case Keys.F3:
                    btnSave_Click(null, null);
                    break;
                case Keys.F7:
                    btnPrint_Click(null, null);
                    break;
                case Keys.Escape:
                    this.Dispose();
                    this.DialogResult = dlgResult;
                    this.Close();
                    break;
            }
        }

        private void cboProvider_SelectedIndexChanged(object sender, EventArgs e)
        {
            lblProvider.Text = cboProvider.Text;
            LoadListByProvider();
        }

        private void dgvList1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.ColumnIndex == dgvList1.Columns["Instalment"].Index)
            {
                decimal d = decimal.Parse(e.Value.ToString());
                e.Value = d.ToString("N1");
            }
        }

        private void dgvList1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            decimal Instalment;
            Instalment = Convert.ToDecimal(dgvList1.Rows[e.RowIndex].Cells["Instalment"].Value);
            dgvList1.Rows[e.RowIndex].Cells["Instalment"].Value = Instalment.ToString("N1");
            TotalRowsPrice();
        }
    }
}